package it.niedermann.android.markdown.markwon.plugins

import android.content.Context
import android.text.TextUtils
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.core.content.ContextCompat
import com.gitee.wsl.common.ui.ext.isDarkThemeActive
import io.noties.markwon.base.AbstractMarkwonPlugin
import io.noties.markwon.base.MarkwonPlugin
import io.noties.markwon.base.R
import it.niedermann.android.markdown.MarkdownUtil
import it.niedermann.android.markdown.model.SearchSpan

class SearchHighlightPlugin(context: Context) : AbstractMarkwonPlugin() {
    private var searchText: CharSequence? = null
    private var current: Int? = null

    @ColorInt
    private var color: Int

    @ColorInt
    private val highlightColor: Int
    private val darkTheme: Boolean

    init {
        color = ContextCompat.getColor(context, R.color.search_color)
        highlightColor = ContextCompat.getColor(context, R.color.bg_highlighted)
        darkTheme = context.isDarkThemeActive
    }

    fun setSearchText(searchText: CharSequence?, current: Int?, textView: TextView) {
        this.current = current
        MarkdownUtil.removeSpans(
            MarkdownUtil.getContentAsSpannable(textView),
            SearchSpan::class.java
        )
        if (TextUtils.isEmpty(searchText)) {
            this.searchText = null
        } else {
            this.searchText = searchText
            afterSetText(textView)
        }
    }

    fun setSearchColor(@ColorInt color: Int, textView: TextView) {
        this.color = color
        afterSetText(textView)
    }

    override fun afterSetText(textView: TextView) {
        super.afterSetText(textView)
        if (searchText != null) {
            val spannable = MarkdownUtil.getContentAsSpannable(textView)
            MarkdownUtil.searchAndColor(
                spannable,
                searchText,
                current,
                color,
                highlightColor,
                darkTheme
            )
        }
    }

    companion object {
        fun create(context: Context): MarkwonPlugin {
            return SearchHighlightPlugin(context)
        }
    }
}